// 2013-9-1下午01:09:21  net.betou.trade.admin.action.ChannelAct.java

package net.betou.trade.admin.action;

import static net.betou.common.page.SimplePage.cpn;
import static net.betou.common.page.SimplePage.cpnPageSize;
import static net.betou.trade.front.action.ContentAct.CONTENT_TPL;
import static net.betou.web.Constants.TPLDIR_CONTENT;
import static net.betou.web.Constants.TPL_SUFFIX;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.page.Pagination;
import net.betou.common.util.DateUtils;
import net.betou.common.util.TradeUtils;
import net.betou.core.service.post.SmsPost;
import net.betou.core.service.post.Task;
import net.betou.trade.action.abs.ActionSupport;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.Content;
import net.betou.trade.main.manager.ChannelMng;
import net.betou.trade.main.manager.ContentMng;
import net.betou.trade.web.Messages;
import net.betou.trade.web.ResponseUtil;
import net.betou.trade.web.WebErrors;
import net.betou.web.freemaker.FreeMarkerBuilder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.SimpleHash;


/**
 * 
 * @author 叶装装
 */
@Controller
public class ContentAct extends ActionSupport< Content >{

	@RequestMapping( "/content/v_list.jspx" )
	public String list( Integer pageSize, Integer pageNo,  String searchProperty, String searchValue, String orderProperty, String orderDirection, HttpServletRequest request, HttpServletResponse response, ModelMap model  ){
		
		pageSize = cpnPageSize( pageSize );
		pageNo = cpn( pageNo );
		
		AgentAndAdmins user = TradeUtils.getAdmin( request ); // 获取当前管理员
		Pagination pagination = manager.getPage( user, searchProperty, searchValue, orderProperty, orderDirection, pageNo, pageSize );
		
		model.addAttribute( "admin", user );
		
		paramToModel( model, pagination, null, pageSize, searchProperty, searchValue, orderProperty, orderDirection, null );
		
		return getListPage( );
	}
	
	@RequestMapping( "/content/v_add.jspx" )
	public String v_add( HttpServletRequest request, ModelMap model ){
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		model.addAttribute( "channelList", channelMng.getList( admin ) );
		return getAddPage( );
	}
	
	@RequestMapping( "/content/o_save.jspx" )
	public String o_save( Content bean,  Integer channelId,   HttpServletRequest request, HttpServletResponse response, ModelMap model ){
		
		WebErrors errors = validateSave( bean );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		bean = manager.save( bean, admin, channelId );
		
		logMng.operating( 0, request, Messages.LOG_CONTENT, "id=" + bean.getId( ) + ",title=" + bean.getTitle( ) );
		
		return "redirect:v_list.jspx";
	}
	
	
	@RequestMapping ( "/content/v_edit.jspx" )
	public String v_edit( Integer id, HttpServletRequest request, ModelMap model ){

		WebErrors errors = validateUpdate( request, id );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		Content bean = manager.findById( id );
		
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		model.addAttribute( "channelList", channelMng.getList( admin ) );
		
		model.addAttribute( "bean", bean );
		
		
		return getUpdatePage( );
	}
	
	@RequestMapping ( "/content/o_update.jspx" )
	public String o_update(  Integer id, Content bean, Integer channelId, HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		WebErrors errors = validateOUpdate( id, admin.getId( ), admin.getSystem( ) );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		bean = manager.update( bean, channelId );
		
		logMng.operating( 1, request, Messages.LOG_CONTENT, "id=" + bean.getId( ) + ",title=" + bean.getTitle( ));
		
		return "redirect:v_list.jspx";
	}
	
	
	@RequestMapping( "/content/o_delete.jspx" )
	public void o_delete( Integer [ ] ids, HttpServletResponse response, HttpServletRequest request ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		ResponseUtil util = validateDelete( ids, admin.getId( ), admin.getSystem( ), response, request );

		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}

		Content [ ] beans = manager.deleteByIds( ids );

		for ( Content bean : beans ){
			logMng.operating( 2, request, Messages.LOG_CONTENT, "id=" + bean.getId( ) + ",title=" + bean.getTitle( ));
		}

		util.addSuccessResponse( Messages.getDeleteSuccessMessage( beans.length ) );

		util.renderJson( );
		return;
		
	}
	
	@RequestMapping( "/content/o_createdPage.jspx" )
	public void o_createPage( Integer[] ids, HttpServletResponse response, HttpServletRequest request ,ModelMap model){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request );
		
		ResponseUtil util = validateCreatePage( ids, admin.getId( ), admin.getSystem( ), response, request );
		
		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}
		
		int successNum = 0;
		
		for(Integer id : ids){
			Content bean = manager.findMyContent( id, admin.getId(), admin.getSystem( ) );
			model.addAttribute( "content", bean );
			ServletContext sc = request.getSession().getServletContext();
			FreeMarkerBuilder fmb = new FreeMarkerBuilder(freemarkerConfig, sc);
			SimpleHash sh = fmb.buildTemplateModel(model, request, response);
			String tpl = "/t/betou/"+TPLDIR_CONTENT+"/"+CONTENT_TPL+TPL_SUFFIX;
			String yyyyMM = DateUtils.getStringOnFormat(bean.getPubDate(), 3);
			File file = new File(sc.getRealPath("/article/content/"+yyyyMM+"/"+bean.getChannel().getId()+"/"+bean.getId()+TPL_SUFFIX));
			fmb.generateFile(tpl, file, sh);
			
			if(FreeMarkerBuilder.getExecResult()){
				manager.update(bean, true);
				util.addSuccessResponse( Messages.DATA_CREATE_PAGE_SUCCESS );
				logMng.operating( 0, request, Messages.LOG_CONTENT, "id=" + bean.getId( ) + ",name=" + bean.getTitle() + ",action=生成静态页面" );
				successNum++;
			}else{
				util.addErrorResponse( Messages.DATA_CREATE_PAGE_ERROR );
			}
		}
		
		if(successNum == 0){
			util.addErrorResponse( Messages.DATA_CREATE_PAGE_ERROR );
		}else if(successNum == ids.length){
			util.addSuccessResponse( Messages.DATA_CREATE_PAGE_SUCCESS );
		}else{
			int errorNum = ids.length-successNum;
			util.addErrorResponse( "静态页面生成出现错误，"+successNum+"条内容成功，"+ errorNum+"条失败！");
		}

		util.renderJson( );
		return;
		
	}
	
	@RequestMapping( "/content/o_send.jspx" )
	public void o_send( Integer id, HttpServletResponse response, HttpServletRequest request ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		ResponseUtil util = ResponseUtil.create( response );
		
		Content bean = manager.findMyContent( id, admin.getId( ), admin.getSystem( ) );
		
		if( bean == null ){
			util.addErrorResponse(  admin.getSystem( ) ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING   );
			util.renderJson( );
			return;
		}
		
		String smsGroup = bean.getChannel( ).getSmsGroup( );
		
		util = validateSmsSend( smsGroup , bean.getDescription( ), response );
		
		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}

		post.setAdmin( bean.getAdmin( ) );
		post.setSmsGroups( smsGroup );
		post.setContent( clearHtml( bean.getDescription( ) ) );
		
		task.addTask( post );
		
		util.addSuccessResponse( Messages.DATA_SMS_SEND_SUCCESS );
		util.renderJson( );
		return;
	}
	
	private ResponseUtil validateDelete( Integer [ ] ids, Integer adminId, Boolean system, HttpServletResponse response, HttpServletRequest request ) {
		ResponseUtil util = ResponseUtil.create( response );

		if( ids == null || ids.length == 0 ){
			util.addErrorResponse( Messages.DATA_NOT_SELECT );
			return util;
		}

		for ( Integer id : ids ){
			Content bean = manager.findMyContent( id, adminId, system );
			if( bean == null ){
				util.addErrorResponse( system ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING );
				break;
			}
		}
		return util;
	}
	
	private WebErrors validateOUpdate( Integer id, Integer adminId, Boolean system ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		Content bean = manager.findMyContent( id, adminId, system );
		
		if( bean == null ){
			errors.addError( Messages.DATA_NOT_OPERATING );
			return errors;
		}
		
		return errors;
		
	}
	
	private WebErrors validateUpdate( HttpServletRequest request, Integer id ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		Content bean = manager.findById( id );
		
		if( bean == null ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		return errors;
			
	}
	
	private WebErrors validateSave( Content bean ){
		WebErrors errors = WebErrors.create( );
		return errors;
	}
	
	private ResponseUtil validateCreatePage( Integer[] ids, Integer adminId, Boolean system, HttpServletResponse response, HttpServletRequest request){
		ResponseUtil util = ResponseUtil.create( response );
		
		if( ids == null || ids.length==0 ){
			util.addErrorResponse( Messages.DATA_NOT_SELECT );
			return util;
		}
		
		for(Integer id : ids){
			Content bean = manager.findMyContent( id, adminId, system );
			
			if( bean == null ){
				util.addErrorResponse( Messages.DATA_NOT_OPERATING );
				return util;
			}
		}
		
		return util;
	}
	
	@Autowired 
	private ChannelMng channelMng;
	
	@Autowired
	private ContentMng manager;
	
	@Autowired
	private SmsPost post;
	
	@Autowired
	protected Task task;
	
	@Autowired
	private FreeMarkerConfigurer freemarkerConfig;

	private static final String DIRECTORY = "content";
	@Override
	protected String getDirectory( ) {
		return DIRECTORY;
	}
}
